package org.sauceggplant.item.man.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.sauceggplant.item.man.dao.ItemDao;
import org.sauceggplant.item.man.dto.ItemDto;
import org.sauceggplant.item.man.po.Item;
import org.sauceggplant.item.man.service.ItemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class ItemServiceImpl extends AbstractServiceImpl implements ItemService {

    private static final Logger logger = LoggerFactory.getLogger(ItemServiceImpl.class);

    private ItemDao itemDao;

    public ItemServiceImpl() {
        itemDao = new ItemDao();
    }

    @Override
    public List<Item> findAll(ItemDto itemDto) {
        try {
            return itemDao.findAll(itemDto, DbConnectionServiceImpl.MYSQL_TYPE);
        } catch (SQLException e) {
            logger.error(ItemServiceImpl.class.getName(), e);
            return null;
        }
    }

    @Override
    public Integer insert(Item item) {
        try {
            if (StringUtils.isEmpty(item.getName())) {
                throw new NullPointerException("Item.name is not null.");
            }
            if (StringUtils.isEmpty(item.getCount())) {
                item.setCount("");
            }
            if (StringUtils.isEmpty(item.getRemark())) {
                item.setRemark("");
            }
            if (null == item.getTypeId()) {
                item.setTypeId(1L);
            }
            if (null == item.getCreateAccount()) {
                item.setCreateAccount(DEFAULT_ACCOUNT);
            }
            if (null == item.getUpdateAccount()) {
                item.setUpdateAccount(DEFAULT_ACCOUNT);
            }
            item.setUuid(uuidService.generateUuid());
            Date now = new Date();
            item.setCreateTime(now);
            item.setUpdateTime(now);
            item.setVersion(1);
            return itemDao.insert(item, DbConnectionServiceImpl.MYSQL_TYPE);
        } catch (SQLException e) {
            logger.error(ItemServiceImpl.class.getName(), e);
            return 0;
        }
    }

    @Override
    public Integer update(Item item) {
        try {
            if (null == item.getUpdateAccount()) {
                item.setUpdateAccount(DEFAULT_ACCOUNT);
            }
            Date now = new Date();
            item.setUpdateTime(now);
            return itemDao.update(item, DbConnectionServiceImpl.MYSQL_TYPE);
        } catch (SQLException e) {
            logger.error(ItemServiceImpl.class.getName(), e);
            return 0;
        }
    }

    @Override
    public Integer delete(Long id) {
        try {
            return itemDao.delete(id, DbConnectionServiceImpl.MYSQL_TYPE);
        } catch (SQLException e) {
            logger.error(ItemServiceImpl.class.getName(), e);
            return 0;
        }
    }
}
